package interaction

import (
	"time"

	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/app/sysparam"

	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core/common"
)

func (c interactionCtrl) putLike(ctx *gin.Context) {
	code := sysparam.IntsLikeCode()

	iityp, id, err := getTypAndID(ctx)
	if err != nil {
		c.ErrBadRequest(ctx, 1, "参数错误", err)
		return
	}
	dctx := c.DDDContext(ctx)
	uid := dctx.UID()
	if uid == "" {
		c.ErrUnauthorized(ctx, "保存失败：未登录")
		return
	}
	if err = c.addOp(dctx, uid, code, reqOp{
		TargetID:   id,
		TargetType: iityp,
		Value:      1,
	}); err != nil {
		c.ErrServerError(ctx, 6, "点赞失败", err)
		return
	}
	c.Success(ctx, nil)
}
func (c interactionCtrl) deleteLike(ctx *gin.Context) {
	code := sysparam.IntsLikeCode()

	iityp, id, err := getTypAndID(ctx)
	if err != nil {
		c.ErrBadRequest(ctx, 1, "参数错误", err)
		return
	}

	dctx := c.DDDContext(ctx)
	uid := dctx.UID()
	if uid == "" {
		c.ErrUnauthorized(ctx, "取消点赞失败：未登录")
		return
	}
	if err := c.deleteOp(dctx, uid, code, reqOp{
		TargetID:   id,
		TargetType: iityp,
	}); err != nil {
		c.ErrServerError(ctx, 5, "取消点赞失败", errors.Wrapf(err, "取消点赞失败"))
		return
	}
	c.Success(ctx, nil)
}

func (c interactionCtrl) queryPageLikeByCode(ctx *gin.Context) {
	code := sysparam.IntsLikeCode()
	sch := c.getOpSearch(ctx)
	sch.Codes = []string{code}
	dctx := c.DDDContext(ctx)
	uid := dctx.UID()
	if uid == "" {
		c.ErrUnauthorized(ctx, "保存失败：未登录")
		return
	}
	sch.UID = []string{uid}
	page := c.GetPageInfo(ctx, common.PageModeID)
	pr, cs, err := c.iiar.QueryPage(dctx, sch, page)
	if err != nil {
		c.ErrServerError(ctx, 30, "查询失败", errors.Wrapf(err, "查询互动交互列表失败"))
		return
	}
	out := make([]respLike, 0, len(cs))
	for _, v := range cs {
		rc := respLike{
			ID:       v.InteractionID,
			UID:      v.UID,
			LikeTime: v.CreTime,
		}
		out = append(out, rc)
	}
	c.SuccessPage(ctx, page, pr, out)
}

type respLike struct {
	ID       string    `json:"id"`        // 互动ｉｄ
	UID      string    `json:"uid"`       // 互动用户
	LikeTime time.Time `json:"Like_time"` // 收藏时间
}
